var api = require('../config/api.js');

/**
 * 封装微信的的request
 */
function request(url, data = {}, method = "GET") {
  let contentType = 'application/json';
  if (method == 'POST') {
    contentType = 'application/x-www-form-urlencoded';
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': contentType,
        'Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res);
        if (res.statusCode === 200) {
            resolve(res.data);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          console.log(res)
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}
/**
 * 判断用户是否登录
 * 已经登录，则返回用户信息
 */
function checkLogin() {
  let userInfo = wx.getStorageSync('userInfo');
  let token = wx.getStorageSync('token');
  console.log('checklogin');
  console.log(userInfo);
  console.log(token);
  
  if (!userInfo || !token) {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  }else{
    let now = new Date().getTime() / 1000;
    if(userInfo.expire_time<now){
        wx.showModal({
            title: '提示',
            showCancel: false,
            content: '登录已过期，请重新登录！',
            success(res) {
              if (res.confirm) {
                  wx.navigateTo({
                      url: '/pages/login/login'
                  })
              }
            }
        })
    }
    return userInfo;
  }
}

function showMsg(msg, status) {
  if(status==1){
    wx.showToast({
      title: msg,
      icon: "success"
    })
  }else{
    wx.showToast({
      title: msg,
      image: '/images/icon_error.png'
    })
  }
}

//统一跳转  go_to('navigateTo','pages/index/index','keyword=张三')
function go_to(type,url,parameter){
  parameter!=undefined?url = '/'+url+'?'+parameter:url = '/'+url;
  switch (type) {
    case 'navigateTo':
      wx.navigateTo({url:url});
      break;
    case 'redirectTo':
      wx.redirectTo({url:url});
      break;
    case 'switchTab':
      wx.switchTab({url:url});
      break;
    case 'reLaunch':
      wx.reLaunch({url:url});
      break;
    default:
      wx.navigateTo({url:url});
      break;
  }
}

module.exports = {
  request,
  showMsg,
  login,
  checkLogin,
  go_to
}
